package com.goldcontrol.cloudweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldcontrol.cloudweb.model.ProjectRepair;
import com.goldcontrol.cloudweb.model.ProjectRepairRecord;
import com.goldcontrol.cloudweb.model.TemplateMsgConstant;
import com.goldcontrol.cloudweb.model.alarm.AlarmTemplateMsgFactory;
import com.goldcontrol.cloudweb.service.ApiService;
import com.goldcontrol.cloudweb.service.RepairService;
import com.goldcontrol.cloudweb.util.MD5Util;
import com.goldcontrol.cloudweb.util.StringUtil;
import com.goldcontrol.cloudweb.weixin.service.WeixinServiceApi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {

    private static Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Autowired
    ApiService apiService;

    @Autowired
    WeixinServiceApi weixinServiceApi;

    @Autowired
    RepairService repairService;

    @RequestMapping(value = "/login",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String login(@RequestBody JSONObject request){
        String tenant = request.getString("tenant");
        String res = weixinServiceApi.login(request.getString("username"),request.getString("password"),tenant);
        JSONObject dataObject = JSONObject.parseObject(res);
        String token = dataObject.getString("data");
        try{
            String info = weixinServiceApi.findUserInfo(token,request.getString("username"));
            JSONObject userInfoObject = JSONObject.parseObject(info);
            dataObject.put("userdata",userInfoObject.getJSONObject("data"));
        }catch (Exception e){
            logger.error("获取userinfo失败",e);
        }
        return dataObject.toJSONString();
    }

    @RequestMapping(value = "/login2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String login2(@RequestBody JSONObject request){
        String res = weixinServiceApi.login2(request.getString("username"),request.getString("password"));
        JSONObject dataObject = JSONObject.parseObject(res);
        String token = dataObject.getString("data");
        try{
            String info = weixinServiceApi.findUserInfo(token,request.getString("username"));
            JSONObject userInfoObject = JSONObject.parseObject(info);
            dataObject.put("userdata",userInfoObject.getJSONObject("data"));
        }catch (Exception e){
            logger.error("获取userinfo失败",e);
        }
        return dataObject.toJSONString();
    }

    @RequestMapping(value = "/bindAccount",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String bindAccount(String username,String password,String openid,String tenant){
        return weixinServiceApi.bindAccount(username,password,openid,tenant);
    }

    @RequestMapping(value = "/bindAccount2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String bindAccount2(String username,String password,String openid){
        return weixinServiceApi.bindAccount2(username,password,openid);
    }

    @RequestMapping(value = "/unbindAccount",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String unbindAccount(String token,String openid){
        return weixinServiceApi.unbindAccount(token,openid);
    }

    @RequestMapping(value = "/unbindAccount2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String unbindAccount2(String token,String openid){
        return weixinServiceApi.unbindAccount(token,openid);
    }

    @RequestMapping(value = "/loginWithOpenid",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String loginWithOpenid(String openid){
        logger.info("使用openid登录:"+openid);
        return weixinServiceApi.loginWithOpenid(openid);
    }

    @RequestMapping(value = "/getProjectsList",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getProjectsList(@RequestParam String token) throws ParseException {
        String result = weixinServiceApi.getProjectsList(token);
        return result;
    }

    @RequestMapping(value = "/test",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String test() throws ParseException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",100);
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/getHistoryData",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getHistoryData(String token,String sDate,String eDate,String devid,String itemid) throws ParseException {
        JSONArray jsonArray = apiService.getItemHistory(token,sDate,eDate,devid,itemid);
        return jsonArray.toJSONString();
    }


    /**
     * 获取最近一小时数据
     * @param token
     * @param devid
     * @param itemid
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getLatestHourHistoryData",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getLatestHourHistoryData(String token,String devid,String itemid){
        Date curDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-1);
        Date oldDate = calendar.getTime();
        String res = apiService.getProjectHistoryData(token,devid,itemid,oldDate.getTime(),curDate.getTime(),1000);
        return res;
    }

    @RequestMapping(value = "/getMultiHistoryData",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getMultiHistoryData(@RequestBody JSONObject jsonObject) throws ParseException {

        String token = jsonObject.getString("token");
        JSONArray itemArray = jsonObject.getJSONArray("items");
        String sTime = jsonObject.getString("sTime");
        String eTime = jsonObject.getString("eTime");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sDate = sdf.parse(sTime);
        Date eDate = sdf.parse(eTime);

        JSONArray jsonArray = new JSONArray();

        for(Object object : itemArray){
            if(object instanceof JSONObject){
                JSONObject itemObject = (JSONObject)object;
                String devid = itemObject.getString("devid");
                String itemid = itemObject.getString("itemid");
                String res = apiService.getProjectHistoryData(token,devid,itemid,sDate.getTime(),eDate.getTime(),1000);
                itemObject.put("data",res);
                jsonArray.add(itemObject);
            }
        }
        JSONObject result = new JSONObject();
        result.put("data",jsonArray);
        return result.toJSONString();
    }



    @RequestMapping(value = "/getLineHistoryData",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getLineHistoryData(@RequestBody JSONObject jsonObject) throws ParseException {
        logger.error("请求getLineHistoryData参数 "+jsonObject.toJSONString());
        int type = jsonObject.getInteger("type");
        String token = jsonObject.getString("token");
        String inDevid = jsonObject.getString("in_devid");
        String inItemId = jsonObject.getString("in_itemid");
        JSONArray inArr = weixinServiceApi.getHistoryLineData(type,token,inDevid,inItemId).getJSONArray("dataArr");
        JSONArray collectDateArr = weixinServiceApi.getHistoryLineData(type,token,inDevid,inItemId).getJSONArray("timeArr");
        String outDevid = jsonObject.getString("out_devid");
        String outItemId = jsonObject.getString("out_itemid");
        JSONArray outArr = weixinServiceApi.getHistoryLineData(type,token,outDevid,outItemId).getJSONArray("dataArr");
        String envDevid = jsonObject.getString("env_devid");
        String envItemId = jsonObject.getString("env_itemid");
        JSONArray envArr = weixinServiceApi.getHistoryLineData(type,token,envDevid,envItemId).getJSONArray("dataArr");

        JSONObject result = new JSONObject();
        result.put("in",inArr);
        result.put("out",outArr);
        result.put("env",envArr);
        if(type == 1){
            result.put("date",collectDateArr);
        }else{
            JSONArray dateArr = weixinServiceApi.getHistoryLineDate(type);
            result.put("date",dateArr);
        }
        return result.toJSONString();
    }

    @RequestMapping(value = "/ctrl",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String ctrl(@RequestBody JSONObject request){
        String token = request.getString("token");
        String devid = request.getString("devid");
        String itemid = request.getString("itemid");
        String value = request.getString("value");
        return weixinServiceApi.sendCtrl(token,devid,itemid,value);
    }

    /**
     * hash
     * token
     * devid
     * itemid
     * sign
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCtrlResult",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getCtrlResult(@RequestBody JSONObject request){
        String token = request.getString("token");
        String devid = request.getString("devid");
        String itemid = request.getString("itemid");
        String sign = request.getString("sign");
        return weixinServiceApi.getCtrlResult(token,devid,itemid,sign);
    }


    @ResponseBody
    @RequestMapping(value = "addRepair",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public String addRepair(@RequestBody JSONObject request){
        JSONObject result = new JSONObject();
        try{
            int id = repairService.getRepairId();
            String projectId = request.getString("projectId");
            String openid = request.getString("openid");
            String title = request.getString("title");
            String content = request.getString("content");
            JSONArray fileList = request.getJSONArray("fileList");

            ProjectRepair projectRepair = new ProjectRepair();
            projectRepair.setRepairId(id);
            projectRepair.setProjectId(projectId);
            projectRepair.setRepairDesc(title);
            projectRepair.setReason(content);
            projectRepair.setWeixinId(openid);
            repairService.addRepair(projectRepair);
            repairService.upoadFile(id,fileList);
            result.put("status",100);
            return result.toJSONString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("addProjectRepair",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "getRepairs")
    public String getRepairs(String openid,String projectId){
        JSONObject result = new JSONObject();
        try{
            JSONObject jsonObject = repairService.getRepairs(openid,"",projectId);
            jsonObject.put("status",100);
            return jsonObject.toJSONString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "getRepairDetail")
    public String getRepairDetail(Integer repairId){
        JSONObject result = new JSONObject();
        try{
            JSONObject jsonObject = repairService.getRepairDetail(repairId);
            jsonObject.put("status",100);
            return jsonObject.toJSONString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepairDetail error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "upload",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public String upload(MultipartFile file){
        JSONObject result = new JSONObject();
        try{
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String fileNewName = MD5Util.get(fileName)+suffix;
            String filePath = repairService.upload(file,fileNewName);
            result.put("status",100);
            result.put("url",filePath);
            return result.toJSONString();
        }catch (Exception e){
            logger.error("addProjectRepair",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "pagination")
    public String pagination(int page,int perPage,String token,String deviceId){
        JSONObject result = new JSONObject();
        try{
            String res = apiService.pagination(page,perPage,token,deviceId);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("pagination error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "paginationList")
    public String paginationList(int page,int perPage,String token){
        JSONObject result = new JSONObject();
        try{
            String res = apiService.paginationList(page,perPage,token);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("paginationList error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @RequestMapping(value = "/createTemplate",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String createTemplate(@RequestBody JSONObject request){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",100);
        try{
            weixinServiceApi.createTemplate(request);
        }catch (Exception e){
            jsonObject.put("status",200);
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/deleteTemplate",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String deleteTemplate(@RequestParam Integer projectId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",100);
        try{
            weixinServiceApi.deleteTemplate(projectId);
        }catch (Exception e){
            jsonObject.put("status",200);
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/getTemplate",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getTemplate(@RequestParam Integer projectId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",100);
        try{
            JSONObject data = weixinServiceApi.getProjectTemplate(projectId);
            jsonObject.put("data",data);
            return jsonObject.toJSONString();
        }catch (Exception e){
            jsonObject.put("status",200);
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/getProjectAlarm",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getProjectAlarm(@RequestParam String projectId,@RequestParam String token,@RequestParam String page,@RequestParam String perPage) throws ParseException {
        return weixinServiceApi.getProjectAlarmData(projectId,token,page,perPage);
    }

    @ResponseBody
    @RequestMapping(value = "/alarm", method = RequestMethod.GET)
    public String receiveAlarms(@RequestParam(value="parameter") String parameter){
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            parameter = URLDecoder.decode(parameter, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(map);
        }
        JSONObject json = JSON.parseObject(parameter);
        Integer deviceId = json.getInteger("deviceId");
        String serialNumber = json.getString("serial_number");
        String deviceName = json.getString("device_name");
        Integer severity = json.getInteger("severity");
        Long htime = json.getLong("htime");
        String itemName = json.getString("item_name");
        String alias = json.getString("alias");
        String ruleName = json.getString("rule_name");
        String alarmDesc = json.getString("alarm_desc");
        JSONArray openIds = json.getJSONArray("openid");
        logger.info("接收到的参数为：");
        logger.info("[deviceId]:" + deviceId);
        logger.info("[serial_number]:" + serialNumber);
        logger.info("[device_name]:" + deviceName);
        logger.info("[severity]:" + severity);
        logger.info("[htime]:" + htime);
        logger.info("[item_name]:" + itemName);
        logger.info("[alias]:" + alias);
        logger.info("[rule_name]:" + ruleName);
        logger.info("[alarm_desc]:" + alarmDesc);
        logger.info("[openid]:" + openIds.toJSONString());
        logger.info("结束.");
        for(Object object : openIds){
            String openId = ((JSONObject)object).getString("weixinId");
            logger.info("ready to send msg to [openid]:" + openId);
            try {
                weixinServiceApi.sendTemplateMsg(openId, AlarmTemplateMsgFactory.produce(openId,
                        TemplateMsgConstant.ALARM_TEMPLATE_ID, TemplateMsgConstant.TEMPLATE_URL,
                        ruleName,
                        AlarmTemplateMsgFactory.generateFirst(serialNumber, deviceName, deviceId),
                        StringUtil.yyyyMMddHHmmss(new Date(htime)),
                        AlarmTemplateMsgFactory.generateRemark(alarmDesc, itemName, alias),
                        TemplateMsgConstant.TEMPLATE_COLOR,
                        AlarmTemplateMsgFactory.isDone(alarmDesc,alias)));
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping(value = "/control",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String control(@RequestParam String token,@RequestParam int project,@RequestParam int val) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        try{
            weixinServiceApi.setProjectControl(token,project,val);
            jsonObject.put("status",100);
        }catch (Exception e){
            jsonObject.put("status",200);
        }
        return jsonObject.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/reply")
    public String reply(@RequestBody JSONObject payLoad){
        JSONObject result = new JSONObject();
        try{
            ProjectRepairRecord record = JSONObject.parseObject(payLoad.toJSONString(),ProjectRepairRecord.class);
            repairService.addRepairRecord(record);
            result.put("status",100);
            return result.toJSONString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getDeviceItemsDefault", method = RequestMethod.GET)
    public String getDeviceItemsDefault(String token,String projectId){
        JSONObject result = new JSONObject();
        try{
            return weixinServiceApi.getDeviceItems(token,projectId);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getDeviceItems")
    public String getDeviceItems(String token,String projectId){
        JSONObject result = new JSONObject();
        try{
            String res =  weixinServiceApi.getDeviceItems(token,projectId);
            JSONObject jsonObject = JSON.parseObject(res);
            JSONArray roomArray = new JSONArray();
            if("100".equals(jsonObject.getString("status"))){
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                if(jsonArray!=null&&jsonArray.size()>0){
                    for(Object o : jsonArray){
                        JSONObject itemObject = (JSONObject)o;
                        String name = itemObject.getString("vdeviceName");
                        if(!(name.contains("主界面") || name.contains("其他"))){
                            JSONObject info = weixinServiceApi.getRoomData(token,name,projectId);
                            itemObject.put("info",info);
                            roomArray.add(itemObject);
                        }
                    }
                }
            }
            result.put("data",roomArray);
            result.put("code",0);
            return result.toJSONString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/updateDeviceName")
    public String updateDeviceName(String token,String id,String name){
        JSONObject result = new JSONObject();
        try{
            return weixinServiceApi.updateDeviceName(token,id,name);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/currentDataDevice")
    public String currentDataDevice(@RequestBody JSONObject request){
        JSONObject result = new JSONObject();
        try{
            return weixinServiceApi.currentDataDevice(request.toJSONString());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/devicelist")
    public String devicelist(String token){
        JSONObject result = new JSONObject();
        try{
            return weixinServiceApi.getDeviceList(token).toJSONString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getRepair error {}",e);
            result.put("status",200);
            return result.toJSONString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/jcm/alarm", method = RequestMethod.GET)
    public String receiveAlarms1(@RequestParam(value="parameter") String parameter){
        logger.error("receiveAlarms1 接收到的参数为:{}",parameter);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            parameter = URLDecoder.decode(parameter, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(map);
        }
        JSONObject json = JSON.parseObject(parameter);
        Integer deviceId = json.getInteger("deviceId");
        String serialNumber = json.getString("serial_number");
        String deviceName = json.getString("device_name");
        Integer severity = json.getInteger("severity");
        Long htime = json.getLong("htime");
        String itemName = json.getString("item_name");
        String alias = json.getString("alias");
        String ruleName = json.getString("rule_name");
        String alarmDesc = json.getString("alarm_desc");
        JSONArray openIds = json.getJSONArray("openid");
        for(Object object : openIds){
            String openId = ((JSONObject)object).getString("weixinId");
            logger.info("ready to send msg to [openid]:" + openId);
            try {
                weixinServiceApi.sendJcmTemplateMsg(openId, AlarmTemplateMsgFactory.produce(openId,
                        TemplateMsgConstant.JCM_ALARM_TEMPLATE_ID, TemplateMsgConstant.TEMPLATE_URL,
                        ruleName,
                        AlarmTemplateMsgFactory.generateFirst(serialNumber, deviceName, deviceId),
                        StringUtil.yyyyMMddHHmmss(new Date(htime)),
                        AlarmTemplateMsgFactory.generateRemark(alarmDesc, itemName, alias),
                        TemplateMsgConstant.TEMPLATE_COLOR,
                        AlarmTemplateMsgFactory.isDone(alarmDesc,alias)));
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        return JSON.toJSONString(map);
    }

    @ResponseBody
    @RequestMapping(value = "/ys/alarm", method = RequestMethod.GET)
    public String receiveAlarms2(@RequestParam(value="parameter") String parameter){
        logger.error("receiveAlarms2 接收到的参数为:{}",parameter);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            parameter = URLDecoder.decode(parameter, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(map);
        }
        JSONObject json = JSON.parseObject(parameter);
        Integer deviceId = json.getInteger("deviceId");
        String serialNumber = json.getString("serial_number");
        String deviceName = json.getString("device_name");
        Integer severity = json.getInteger("severity");
        Long htime = json.getLong("htime");
        String itemName = json.getString("item_name");
        String alias = json.getString("alias");
        String ruleName = json.getString("rule_name");
        String alarmDesc = json.getString("alarm_desc");
        JSONArray openIds = json.getJSONArray("openid");
        for(Object object : openIds){
            String openId = ((JSONObject)object).getString("weixinId");
            logger.info("ready to send msg to [openid]:" + openId);
            try {
                weixinServiceApi.sendYsTemplateMsg(openId, AlarmTemplateMsgFactory.produce(openId,
                        TemplateMsgConstant.YS_ALARM_TEMPLATE_ID, TemplateMsgConstant.TEMPLATE_URL,
                        ruleName,
                        AlarmTemplateMsgFactory.generateFirst(serialNumber, deviceName, deviceId),
                        StringUtil.yyyyMMddHHmmss(new Date(htime)),
                        AlarmTemplateMsgFactory.generateRemark(alarmDesc, itemName, alias),
                        TemplateMsgConstant.TEMPLATE_COLOR,
                        AlarmTemplateMsgFactory.isDone(alarmDesc,alias)));
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        return JSON.toJSONString(map);
    }

}
